<template>
  <div class="refund-task-management">
    <!-- 操作按钮区域 -->
    <div class="d-flex justify-content-between align-items-center mb-3">
      <div>
        <button 
          type="button" 
          class="btn btn-primary me-2"
          @click="createRefundTask"
          :disabled="loading || !canCreateNewTask"
          :title="getCreateTaskButtonTitle()"
        >
          <i class="bi bi-plus-circle"></i>
          <span v-if="loading">创建中...</span>
          <span v-else>创建退费任务</span>
        </button>
        <button 
          type="button" 
          class="btn btn-outline-secondary"
          @click="refreshData"
          :disabled="loading"
        >
          <i class="bi bi-arrow-clockwise"></i> 刷新
        </button>
        <!-- 创建任务提示信息 -->
        <div v-if="!canCreateNewTask && masterData.length > 0" class="mt-2">
          <small class="text-warning">
            <i class="bi bi-exclamation-triangle"></i>
            需要完成当前任务中所有患者的联系工作后，才能创建新的退费任务
          </small>
        </div>
      </div>
    </div>

    <!-- 主表数据显示 -->
    <div class="card mb-4" v-if="masterData.length > 0">
      <div class="card-header">
        <h5 class="mb-0">
          <i class="bi bi-list-task"></i> 退费任务主表数据
        </h5>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-striped table-hover">
            <thead class="table-dark">
              <tr>
                <th>任务ID</th>
                <th>创建时间</th>
                <th>联系进度</th>
                <th>总金额</th>
                <th>总记录数</th>
                <th>备注</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in masterData" :key="item.id">
                <td>{{ item.id }}</td>
                <td>{{ formatDateTime(item.inputDate) }}</td>
                <td>
                  <div class="contact-progress">
                    <!-- 联系进度条 -->
                    <div class="progress mb-1" style="height: 8px;">
                      <div 
                        class="progress-bar" 
                        :class="getProgressBarClass(item.contactedCount, item.accountCount)"
                        :style="{ width: getProgressPercentage(item.contactedCount, item.accountCount) + '%' }"
                      ></div>
                    </div>
                    <!-- 联系统计数文字 -->
                    <small class="text-muted">
                      已联系: <span class="text-success fw-bold">{{ item.contactedCount || 0 }}</span> / 
                      总计: <span class="fw-bold">{{ item.accountCount || 0 }}</span>
                      <span class="text-primary ms-1">({{ getProgressPercentage(item.contactedCount, item.accountCount) }}%)</span>
                    </small>
                  </div>
                </td>
                <td class="text-end">{{ formatCurrency(item.accountSumBalance) }}</td>
                <td class="text-center">{{ item.accountCount }}</td>
                <td>{{ item.notes || '-' }}</td>
                <td>
                  <button 
                    type="button" 
                    class="btn btn-sm btn-outline-primary"
                    @click="showDetails(item.id)"
                  >
                    <i class="bi bi-eye"></i> 详情
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 无数据提示 -->
    <div class="alert alert-info text-center" v-if="masterData.length === 0 && !loading">
      <i class="bi bi-info-circle"></i>
      暂无退费任务数据，请点击"创建退费任务"按钮初始化数据
    </div>

    <!-- 加载状态 -->
    <div class="text-center" v-if="loading">
      <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">加载中...</span>
      </div>
      <p class="mt-2">{{ loadingText }}</p>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="退费任务详情"
      width="90%"
      :close-on-click-modal="false"
    >
      <template #header>
        <span>
          <i class="bi bi-list-ul"></i> 退费任务详情 - 任务ID: {{ selectedMasterId }}
        </span>
      </template>
      
      <div v-if="detailLoading" class="text-center">
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">加载详情中...</span>
        </div>
      </div>
      
      <div v-else-if="detailData.length > 0">
        <!-- 排序说明 -->
        <div class="mb-3">
          <div class="alert alert-info py-2">
            <i class="bi bi-info-circle"></i>
            <small>
              <strong>排序说明：</strong>未联系患者（联系次数为0）优先显示，方便及时处理
            </small>
          </div>
        </div>
        
        <div class="table-responsive">
          <table class="table table-striped table-sm">
            <thead class="table-dark">
              <tr>
                <th>患者姓名</th>
                <th>身份证号</th>
                <th>性别</th>
                <th>电话号码</th>
                <th>余额</th>
                <th>联系次数</th>
                <th>首次联系结果</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="detail in sortedDetailData" :key="detail.id" :class="getRowClass(detail)">
                <td>{{ detail.patName || '-' }}</td>
                <td>{{ maskIdNumber(detail.idNumber) }}</td>
                <td>{{ detail.sex || '-' }}</td>
                <td>
                  <button 
                    type="button" 
                    class="btn btn-sm btn-outline-info"
                    @click="showContactRecord(detail)"
                    :title="'点击查看完整电话号码和联系记录'"
                  >
                    <i class="bi bi-telephone"></i> {{ maskPhoneNumber(detail.phoneNumber) }}
                  </button>
                </td>
                <td class="text-end">{{ formatCurrency(detail.balance) }}</td>
                <td class="text-center">
                  <span :class="getContactCountClass(detail.contactCount)">
                    {{ detail.contactCount || 0 }}
                  </span>
                </td>
                <td>
                  <span v-if="detail.notes1" class="text-success">
                    <i class="bi bi-check-circle"></i> {{ detail.notes1 }}
                  </span>
                  <span v-else class="text-muted">
                    <i class="bi bi-dash-circle"></i> 未联系
                  </span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="mt-3">
          <div class="row">
            <div class="col-md-6">
              <small class="text-muted">
                共 {{ detailData.length }} 条详情记录
              </small>
            </div>
            <div class="col-md-6 text-end">
              <small class="text-muted">
                未联系：<span class="text-warning fw-bold">{{ uncontactedCount }}</span> 人 | 
                已联系：<span class="text-success fw-bold">{{ contactedCount }}</span> 人
              </small>
            </div>
          </div>
        </div>
      </div>
      
      <div v-else class="alert alert-warning">
        <i class="bi bi-exclamation-triangle"></i>
        该任务暂无详情数据
      </div>
      
      <template #footer>
        <div class="d-flex justify-content-between align-items-center w-100">
          <div>
            <el-button 
              @click="prevDetail" 
              :disabled="currentDetailIndex <= 0"
              type="primary"
              plain
            >
              <i class="bi bi-chevron-left"></i> 上一条
            </el-button>
            <el-button 
              @click="nextDetail" 
              :disabled="currentDetailIndex >= detailData.length - 1"
              type="primary"
              plain
            >
              下一条 <i class="bi bi-chevron-right"></i>
            </el-button>
          </div>
          <div>
            <span class="text-muted me-3">
              {{ currentDetailIndex + 1 }} / {{ detailData.length }}
            </span>
            <el-button @click="showDetailDialog = false">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    <!-- 联系记录对话框 -->
    <div 
      class="modal fade" 
      id="contactModal" 
      tabindex="-1" 
      aria-labelledby="contactModalLabel" 
      aria-hidden="true"
      :class="{ show: showContactDialog }"
      :style="{ display: showContactDialog ? 'block' : 'none' }"
    >
      <div class="modal-dialog modal-xl">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="contactModalLabel">
              <i class="bi bi-person-lines-fill"></i> 联系记录详情 - {{ selectedContactDetail?.patName }}
            </h5>
            <button type="button" class="btn-close" @click="showContactDialog = false" aria-label="Close"></button>
          </div>
          
          <div class="modal-body" v-if="selectedContactDetail">
            <!-- 基本信息 -->
            <div class="card mb-3">
              <div class="card-header">
                <h6 class="mb-0"><i class="bi bi-info-circle"></i> 基本信息</h6>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-6">
                    <p><strong>患者姓名：</strong>{{ selectedContactDetail.patName || '-' }}</p>
                    <p><strong>性别：</strong>{{ selectedContactDetail.sex || '-' }}</p>
                    <p><strong>身份证号：</strong>{{ selectedContactDetail.idNumber || '-' }}</p>
                    <p><strong>联系人：</strong>{{ selectedContactDetail.nextOfKin || '-' }}</p>
                    <p><strong>监护人：</strong>{{ selectedContactDetail.guardianName || '-' }}</p>
                  </div>
                  <div class="col-md-6">
                    <p><strong>电话号码：</strong>
                      <span class="phone-number-highlight">
                        <i class="bi bi-telephone-fill text-primary"></i>
                        <strong class="text-primary fs-5">{{ formatPhoneNumber(selectedContactDetail.phoneNumber) || '-' }}</strong>
                        <button 
                          v-if="selectedContactDetail.phoneNumber" 
                          class="btn btn-sm btn-outline-primary ms-2"
                          @click="copyPhoneNumber(selectedContactDetail.phoneNumber)"
                          title="复制电话号码"
                        >
                          <i class="bi bi-copy"></i>
                        </button>
                      </span>
                    </p>
                    <p><strong>联系人电话：</strong>
                      <span v-if="selectedContactDetail.nextOfKinPhone" class="phone-number-highlight">
                        <i class="bi bi-telephone text-success"></i>
                        <strong class="text-success">{{ formatPhoneNumber(selectedContactDetail.nextOfKinPhone) }}</strong>
                        <button 
                          class="btn btn-sm btn-outline-success ms-2"
                          @click="copyPhoneNumber(selectedContactDetail.nextOfKinPhone)"
                          title="复制联系人电话"
                        >
                          <i class="bi bi-copy"></i>
                        </button>
                      </span>
                      <span v-else class="text-muted">-</span>
                    </p>
                    <p><strong>监护人证件号：</strong>{{ selectedContactDetail.guardianIdcode || '-' }}</p>
                    <p><strong>余额：</strong>{{ formatCurrency(selectedContactDetail.balance) }}</p>
                    <p><strong>总联系次数：</strong>{{ selectedContactDetail.contactCount || 0 }}</p>
                  </div>
                </div>
                <!-- HIS余额信息 -->
                <div class="row mt-2">
                  <div class="col-md-6">
                    <div class="d-flex align-items-center">
                      <strong class="me-2">HIS当前余额:</strong>
                      <span v-if="patientBalanceLoading" class="text-muted">
                        <i class="bi bi-hourglass-split"></i> 查询中...
                      </span>
                      <span v-else-if="patientBalanceError" class="text-danger">
                        <i class="bi bi-exclamation-triangle"></i> {{ patientBalanceError }}
                      </span>
                      <span v-else class="fw-bold" :class="patientBalance > 0 ? 'text-success' : 'text-warning'">
                        ¥{{ (patientBalance || 0).toFixed(2) }}
                        <span v-if="patientBalance === 0" class="text-muted ms-2">
                          <i class="bi bi-info-circle"></i> 余额为0，无法填写联系记录
                        </span>
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 沟通指引卡片 -->
            <div class="card mb-3">
              <div class="card-header">
                <h6 class="mb-0">
                  <i class="bi bi-chat-dots"></i> 沟通指引
                  <button 
                    class="btn btn-sm btn-outline-secondary ms-2"
                    @click="toggleGuideExpanded"
                    :title="guideExpanded ? '收起指引' : '展开指引'"
                  >
                    <i :class="guideExpanded ? 'bi bi-chevron-up' : 'bi bi-chevron-down'"></i>
                  </button>
                </h6>
              </div>
              <div class="card-body" v-show="guideExpanded">
                <div class="row">
                  <!-- 沟通术语 -->
                  <div class="col-md-6">
                    <h6 class="text-primary"><i class="bi bi-chat-text"></i> 沟通术语</h6>
                    <div class="communication-terms">
                      <div 
                        v-for="(term, index) in communicationGuide.terms" 
                        :key="index"
                        class="term-item mb-2"
                      >
                        <div class="term-title fw-bold text-secondary">{{ term.title }}：</div>
                        <div class="term-content small text-muted">{{ term.content }}</div>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 常用话术 -->
                  <div class="col-md-6">
                    <h6 class="text-success"><i class="bi bi-list-check"></i> 常用话术</h6>
                    <div class="communication-scripts">
                      <div 
                        v-for="(script, index) in communicationGuide.scripts" 
                        :key="index"
                        class="script-category mb-3"
                      >
                        <div class="category-title fw-bold text-info mb-1">{{ script.category }}</div>
                        <div class="script-items">
                          <div 
                            v-for="(item, itemIndex) in script.items" 
                            :key="itemIndex"
                            class="script-item small text-muted mb-1"
                            style="cursor: pointer;"
                            @click="copyToClipboard(item)"
                            title="点击复制"
                          >
                            <i class="bi bi-dot"></i> {{ item }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 注意事项 -->
                <div class="row mt-3">
                  <div class="col-12">
                    <h6 class="text-warning"><i class="bi bi-exclamation-triangle"></i> 注意事项</h6>
                    <div class="notes-list">
                      <div 
                        v-for="(note, index) in communicationGuide.notes" 
                        :key="index"
                        class="note-item small text-muted mb-1"
                      >
                        <i class="bi bi-check-circle text-warning"></i> {{ note }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 联系记录 -->
             <div class="card">
               <div class="card-header d-flex justify-content-between align-items-center">
                 <h6 class="mb-0"><i class="bi bi-clock-history"></i> 联系记录</h6>
                 <div class="d-flex align-items-center">
                   <!-- 导航按钮 -->
                   <div class="me-3">
                     <button 
                       type="button" 
                       class="btn btn-sm btn-outline-primary me-2"
                       :disabled="currentContactIndex <= 0"
                       @click="prevContactRecord"
                       title="上一条联系记录"
                     >
                       <i class="bi bi-chevron-left"></i> 上一条
                     </button>
                     <button 
                       type="button" 
                       class="btn btn-sm btn-outline-primary me-2"
                       :disabled="currentContactIndex >= sortedDetailData.length - 1"
                       @click="nextContactRecord"
                       title="下一条联系记录"
                     >
                       下一条 <i class="bi bi-chevron-right"></i>
                     </button>
                     <span class="text-muted small">
                       {{ currentContactIndex + 1 }} / {{ sortedDetailData.length }}
                     </span>
                   </div>
                   <!-- 保存按钮和状态提示 -->
                   <div class="d-flex align-items-center">
                     <button 
                       type="button" 
                       class="btn btn-sm btn-success"
                       :disabled="!hasContactResultChanges || patientBalance === 0"
                       @click="saveContactRecord"
                       style="min-width: 80px;"
                     >
                       <i class="bi bi-check"></i> 保存
                     </button>
                     <!-- 固定宽度的状态提示区域，避免按钮位置变动 -->
                     <div class="ms-2" style="min-width: 280px; min-height: 20px;">
                       <div v-if="hasContactResultChanges" class="text-success small">
                         <i class="bi bi-check-circle"></i> 可以保存联系结果
                       </div>
                       <div v-else-if="hasUnsavedChanges && !hasContactResultChanges" class="text-warning small">
                         <i class="bi bi-exclamation-triangle"></i> 仅填写备注无法保存，需要选择联系结果
                       </div>
                       <div v-if="patientBalance === 0" class="text-warning small">
                         <i class="bi bi-exclamation-triangle"></i> 患者余额为0，无法保存
                       </div>
                     </div>
                   </div>
                 </div>
               </div>
               <div class="card-body">
                 <div class="table-responsive">
                   <table class="table table-striped table-sm">
                     <thead class="table-light">
                       <tr>
                         <th width="15%">联系次序</th>
                         <th width="25%">联系时间</th>
                         <th width="30%">联系结果</th>
                         <th width="30%">备注</th>
                       </tr>
                     </thead>
                     <tbody>
                       <tr v-for="record in getContactRecords(selectedContactDetail)" :key="record.index">
                         <td class="text-center">第{{ record.index }}次</td>
                         <td>
                           <span>{{ formatDateTime(record.contactTime) }}</span>
                         </td>
                         <td>
                           <!-- 已保存的联系结果显示为只读 -->
                           <span v-if="isContactRecordSaved(record.index)" class="text-success">
                             <i class="bi bi-check-circle"></i> {{ record.notes || '-' }}
                           </span>
                           <!-- 可编辑的联系结果 -->
                           <select 
                             v-else-if="canEditContactRecord(record.index) && patientBalance > 0"
                             class="form-select form-select-sm"
                             v-model="selectedContactDetail[`notes${record.index}`]"
                             @change="onContactResultChange(record.index)"
                           >
                             <option value="" disabled>请选择联系结果</option>
                             <option 
                               v-for="option in contactResultOptions" 
                               :key="option.id"
                               :value="option.itemName"
                             >
                               {{ option.itemName }}
                             </option>
                           </select>
                           <!-- 余额为0时的提示 -->
                           <span v-else-if="canEditContactRecord(record.index) && patientBalance === 0" class="text-warning">
                             <i class="bi bi-exclamation-triangle"></i> 患者余额为0，无法填写
                           </span>
                           <!-- 不可编辑状态 -->
                           <span v-else class="text-muted">
                             <i class="bi bi-lock"></i> 请先完成第{{ record.index - 1 }}次联系
                           </span>
                         </td>
                         <td>
                           <!-- 已保存的备注显示为只读 -->
                           <span v-if="isContactRecordSaved(record.index)" class="text-success">
                             {{ record.userNotes || '-' }}
                           </span>
                           <!-- 可编辑的备注 -->
                           <textarea 
                             v-else-if="canEditContactRecord(record.index) && patientBalance > 0"
                             class="form-control form-control-sm"
                             rows="2"
                             v-model="selectedContactDetail[`userNotes${record.index}`]"
                             placeholder="请输入备注信息"
                             @input="onUserNotesInput(record.index)"
                           ></textarea>
                           <!-- 余额为0时的提示 -->
                           <span v-else-if="canEditContactRecord(record.index) && patientBalance === 0" class="text-warning">
                             <i class="bi bi-exclamation-triangle"></i> 患者余额为0，无法填写
                           </span>
                           <!-- 不可编辑状态 -->
                           <span v-else class="text-muted">-</span>
                         </td>
                       </tr>
                     </tbody>
                   </table>
                 </div>
                 <div v-if="getContactRecords(selectedContactDetail).length === 0" class="text-center text-muted">
                   <i class="bi bi-inbox"></i> 暂无联系记录
                 </div>
               </div>
             </div>
          </div>
          
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="closeContactDialog">关闭</button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 模态框背景遮罩 -->
    <div 
      class="modal-backdrop fade" 
      :class="{ show: showContactDialog }"
      v-if="showContactDialog"
      @click="closeContactDialog"
    ></div>

    <!-- 保存后操作选择对话框 -->
    <div 
      class="modal fade" 
      id="saveActionModal" 
      tabindex="-1" 
      aria-labelledby="saveActionModalLabel" 
      aria-hidden="true"
      :class="{ show: showSaveActionDialogFlag }"
      :style="{ display: showSaveActionDialogFlag ? 'block' : 'none' }"
    >
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header bg-success text-white">
            <h5 class="modal-title" id="saveActionModalLabel">
              <i class="bi bi-check-circle"></i> 保存成功
            </h5>
          </div>
          <div class="modal-body text-center py-4">
            <div class="mb-3">
              <i class="bi bi-check-circle-fill text-success" style="font-size: 3rem;"></i>
            </div>
            <h6 class="mb-3">联系记录已成功保存！</h6>
            <p class="text-muted mb-4">请选择下一步操作：</p>
            
            <div class="d-grid gap-3">
              <!-- 跳到下一条按钮 - 更明显的位置和样式 -->
              <button 
                type="button" 
                class="btn btn-primary btn-lg"
                @click="goToNextRecord"
              >
                <i class="bi bi-arrow-right-circle"></i> 跳到下一条记录
                <small class="d-block text-white-50 mt-1">继续联系下一位患者</small>
              </button>
              
              <!-- 继续处理当前记录按钮 -->
              <button 
                type="button" 
                class="btn btn-outline-secondary"
                @click="stayCurrentRecord"
              >
                <i class="bi bi-pencil-square"></i> 继续处理当前记录
                <small class="d-block text-muted mt-1">添加更多联系记录</small>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 保存后选择对话框的背景遮罩 -->
    <div 
      class="modal-backdrop fade" 
      :class="{ show: showSaveActionDialogFlag }"
      v-if="showSaveActionDialogFlag"
      @click="stayCurrentRecord"
    ></div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import api from '@/utils/api'
import { useAuthStore } from '@/stores/auth'
import communicationGuide from '@/config/communicationGuide'
// import userBehaviorService from '@/services/userBehaviorService'

// 获取认证store
const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const loadingText = ref('加载中...')
const masterData = ref([])
const detailData = ref([])
const detailLoading = ref(false)
const selectedMasterId = ref(null)
const showDetailDialog = ref(false)
const currentDetailIndex = ref(0)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)

// 搜索表单
const searchForm = ref({
  taskName: '',
  status: '',
  startDate: '',
  endDate: ''
})

// 页面加载时获取数据
onMounted(() => {
  loadMasterData()
})

// Toast 提示函数
const showToast = (message, type = 'info') => {
  const alertClass = {
    'success': 'alert-success',
    'error': 'alert-danger',
    'warning': 'alert-warning',
    'info': 'alert-info'
  }[type] || 'alert-info'

  const toast = document.createElement('div')
  toast.className = `alert ${alertClass} alert-dismissible fade show position-fixed`
  toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;'
  toast.innerHTML = `
    ${message}
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  `

  document.body.appendChild(toast)

  setTimeout(() => {
    if (toast.parentNode) {
      toast.parentNode.removeChild(toast)
    }
  }, 3000)
}

// 加载主表数据
const loadMasterData = async () => {
  try {
    // 检查用户登录状态
    if (!authStore.isAuthenticated || !authStore.user) {
      showToast('用户未登录，请先登录', 'error')
      return
    }

    loading.value = true
    loadingText.value = '加载退费任务数据...'
    
    // 使用当前用户的username查询任务
    const response = await api.post('/api/RefundTaskMaster/get-by-username', {
      username: authStore.user.username
    })
    
    masterData.value = response.data || []
    totalCount.value = masterData.value.length
    
    // 为每个任务加载联系统计数信息
    if (masterData.value.length > 0) {
      await loadContactStatsForAllTasks()
      await loadLatestTaskDetails()
    } else {
      latestTaskDetails.value = []
    }
  } catch (error) {
    console.error('加载主表数据失败:', error)
    showToast('加载数据失败: ' + (error.response?.data?.message || error.message), 'error')
  } finally {
    loading.value = false
  }
}

// 为所有任务加载联系统计数信息
const loadContactStatsForAllTasks = async () => {
  try {
    // 并行加载所有任务的详情数据来计算联系统计数
    const promises = masterData.value.map(async (task) => {
      try {
        const response = await api.post('/api/RefundTaskDetail/get-by-master-id', {
          id: task.id
        })
        
        const details = response.data || []
        // 计算已联系的患者数量（联系次数大于0）
        const contactedCount = details.filter(detail => (detail.contactCount || 0) > 0).length
        
        // 将联系统计数信息添加到任务对象中
        task.contactedCount = contactedCount
        
        return task
      } catch (error) {
        console.error(`加载任务 ${task.id} 的详情失败:`, error)
        // 如果加载失败，设置默认值
        task.contactedCount = 0
        return task
      }
    })
    
    await Promise.all(promises)
  } catch (error) {
    console.error('加载联系统计数信息失败:', error)
  }
}

// 加载最新任务的详情数据
const loadLatestTaskDetails = async () => {
  try {
    if (masterData.value.length === 0) {
      latestTaskDetails.value = []
      return
    }
    
    // 获取最新的任务（按创建时间排序，取第一个）
    const latestTask = masterData.value.reduce((latest, current) => {
      const latestDate = new Date(latest.inputDate)
      const currentDate = new Date(current.inputDate)
      return currentDate > latestDate ? current : latest
    })
    
    // 加载最新任务的详情数据
    const response = await api.post('/api/RefundTaskDetail/get-by-master-id', {
      id: latestTask.id
    })
    
    latestTaskDetails.value = response.data || []
  } catch (error) {
    console.error('加载最新任务详情失败:', error)
    latestTaskDetails.value = []
  }
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
  loadMasterData()
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadMasterData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    taskName: '',
    status: '',
    startDate: '',
    endDate: ''
  }
  currentPage.value = 1
  loadMasterData()
}

// 创建退费任务
const createRefundTask = async () => {
  try {
    // 检查用户登录状态
    if (!authStore.isAuthenticated || !authStore.user) {
      showToast('用户未登录，请先登录', 'error')
      return
    }

    // 检查是否可以创建新任务
    if (!canCreateNewTask.value) {
      const uncontactedCount = latestTaskDetails.value.filter(detail => (detail.contactCount || 0) === 0).length
      showToast(`当前任务中还有 ${uncontactedCount} 位患者未联系，请先完成联系工作后再创建新任务`, 'warning')
      return
    }

    loading.value = true
    loadingText.value = '正在创建退费任务...'
    
    // 从当前登录用户获取信息，构建正确的请求数据
    const currentUser = authStore.user
    
    const requestData = {
      username: currentUser.username,
      fullname: currentUser.fullName || currentUser.username,
      accountCount: 0,
      accountSumBalance: 0
    }
    
    const response = await api.post('/api/RefundTaskMaster/create-with-his-data', requestData)
    
    if (response.data && response.data.id) {
      showToast('退费任务创建成功！已从HIS数据库导入数据', 'success')
      // 重新加载数据
      await loadMasterData()
    } else {
      showToast('创建失败: ' + (response.data?.message || '未知错误'), 'error')
    }
  } catch (error) {
    console.error('创建退费任务失败:', error)
    showToast('创建失败: ' + (error.response?.data?.message || error.message), 'error')
  } finally {
    loading.value = false
  }
}

// 显示详情
const showDetails = async (masterId) => {
  try {
    // 跟踪查看详情行为
    // await userBehaviorService.trackViewDetails(masterId)
    
    selectedMasterId.value = masterId
    detailLoading.value = true
    detailData.value = []
    currentDetailIndex.value = 0
    
    // 显示对话框
    showDetailDialog.value = true
    
    // 加载详情数据 - 使用正确的接口
    const response = await api.post('/api/RefundTaskDetail/get-by-master-id', {
      id: masterId
    })
    
    if (response.data) {
      detailData.value = response.data || []
    } else {
      showToast('加载详情失败: ' + (response.data?.message || '未知错误'), 'error')
    }
  } catch (error) {
    console.error('加载详情数据失败:', error)
    showToast('加载详情失败: ' + (error.response?.data?.message || error.message), 'error')
  } finally {
    detailLoading.value = false
  }
}

// 身份证号码脱敏处理
const maskIdNumber = (idNumber) => {
  if (!idNumber || idNumber.length < 10) return idNumber || '-'
  // 显示前6位和后4位，中间用*号替代
  const start = idNumber.substring(0, 6)
  const end = idNumber.substring(idNumber.length - 4)
  const middle = '*'.repeat(idNumber.length - 10)
  return start + middle + end
}

// 电话号码脱敏处理
const maskPhoneNumber = (phoneNumber) => {
  if (!phoneNumber || phoneNumber.length < 7) return phoneNumber || '-'
  // 显示前3位和后4位，中间用*号替代
  const start = phoneNumber.substring(0, 3)
  const end = phoneNumber.substring(phoneNumber.length - 4)
  const middle = '****'
  return start + middle + end
}

// 电话号码格式化处理（如：13788026032 -> 137-8802-6032）
const formatPhoneNumber = (phoneNumber) => {
  if (!phoneNumber) return '-'
  
  // 移除所有非数字字符
  const cleanNumber = phoneNumber.toString().replace(/\D/g, '')
  
  // 中国手机号码格式化（11位）
  if (cleanNumber.length === 11) {
    return `${cleanNumber.substring(0, 3)}-${cleanNumber.substring(3, 7)}-${cleanNumber.substring(7)}`
  }
  
  // 固定电话格式化（7-8位，可能带区号）
  if (cleanNumber.length >= 7 && cleanNumber.length <= 12) {
    if (cleanNumber.length === 7) {
      // 7位固话：xxx-xxxx
      return `${cleanNumber.substring(0, 3)}-${cleanNumber.substring(3)}`
    } else if (cleanNumber.length === 8) {
      // 8位固话：xxxx-xxxx
      return `${cleanNumber.substring(0, 4)}-${cleanNumber.substring(4)}`
    } else if (cleanNumber.length === 10) {
      // 10位带区号：xxx-xxx-xxxx
      return `${cleanNumber.substring(0, 3)}-${cleanNumber.substring(3, 6)}-${cleanNumber.substring(6)}`
    } else if (cleanNumber.length === 11) {
      // 11位手机号：xxx-xxxx-xxxx
      return `${cleanNumber.substring(0, 3)}-${cleanNumber.substring(3, 7)}-${cleanNumber.substring(7)}`
    } else if (cleanNumber.length === 12) {
      // 12位带区号：xxxx-xxx-xxxx
      return `${cleanNumber.substring(0, 4)}-${cleanNumber.substring(4, 7)}-${cleanNumber.substring(7)}`
    }
  }
  
  // 其他情况返回原始号码
  return phoneNumber
}

// 联系记录相关状态
const showContactDialog = ref(false)
const selectedContactDetail = ref(null)
const currentContactIndex = ref(0) // 当前联系记录索引
const contactResultOptions = ref([]) // 联系结果选项
const originalContactData = ref(null) // 原始数据备份，用于检测更改
const hasUnsavedChanges = ref(false) // 是否有未保存的更改
const hasContactResultChanges = ref(false) // 是否有联系结果的更改

// 患者余额相关状态
const patientBalance = ref(0) // 患者HIS余额
const patientBalanceLoading = ref(false) // 余额查询加载状态
const patientBalanceError = ref('') // 余额查询错误信息

// 沟通指引相关状态
const guideExpanded = ref(false)

// 最新任务的详情数据（用于检查联系次数）
const latestTaskDetails = ref([])

// 计算属性：是否可以创建新的退费任务
const canCreateNewTask = computed(() => {
  // 如果没有任何任务，可以创建（第一次创建）
  if (masterData.value.length === 0) {
    return true
  }
  
  // 如果最新任务的详情数据为空，暂时不允许创建
  if (latestTaskDetails.value.length === 0) {
    return false
  }
  
  // 检查最新任务的所有明细记录是否都有联系次数大于0
  return latestTaskDetails.value.every(detail => (detail.contactCount || 0) > 0)
})

// 计算属性：排序后的详情数据
const sortedDetailData = computed(() => {
  if (!detailData.value || detailData.value.length === 0) {
    return []
  }
  
  // 创建副本进行排序，避免修改原数组
  const sorted = [...detailData.value]
  
  // 排序规则：联系次数为0的排在前面，然后按联系次数升序，最后按患者姓名排序
  return sorted.sort((a, b) => {
    const aContactCount = a.contactCount || 0
    const bContactCount = b.contactCount || 0
    
    // 首先按联系次数排序（0在前）
    if (aContactCount !== bContactCount) {
      return aContactCount - bContactCount
    }
    
    // 联系次数相同时，按患者姓名排序
    const aName = a.patName || ''
    const bName = b.patName || ''
    return aName.localeCompare(bName, 'zh-CN')
  })
})

// 计算属性：未联系患者数量
const uncontactedCount = computed(() => {
  return detailData.value.filter(detail => (detail.contactCount || 0) === 0).length
})

// 计算属性：已联系患者数量
const contactedCount = computed(() => {
  return detailData.value.filter(detail => (detail.contactCount || 0) > 0).length
})

// 显示联系记录
const showContactRecord = async (detail) => {
  try {
    // 先开始用户行为监控会话
    // const sessionId = await userBehaviorService.startSession(
    //   detail.id,  // taskDetailId - 使用详情记录的ID作为任务详情ID
    //   detail.patientId,
    //   detail.patName,
    //   detail.phoneNumber
    // )
    
    // 确保会话建立成功后再跟踪查看联系记录行为
    // if (sessionId) {
    //   // 添加小延迟确保会话完全建立
    //   await new Promise(resolve => setTimeout(resolve, 100))
    //   await userBehaviorService.trackViewContact(detail.patientId, detail.phoneNumber)
    // } else {
    //   console.warn('会话建立失败，无法跟踪用户行为')
    // }
  } catch (error) {
    console.error('启动用户行为监控失败:', error)
  }
  
  selectedContactDetail.value = detail
  // 修改：基于排序后的数据设置索引，确保导航逻辑正确
  currentContactIndex.value = sortedDetailData.value.findIndex(item => item.id === detail.id)
  // 备份原始数据
  originalContactData.value = JSON.parse(JSON.stringify(detail))
  hasUnsavedChanges.value = false
  showContactDialog.value = true
  
  // 加载联系结果字典数据
  await loadContactResultOptions()
  
  // 查询患者HIS余额
  await loadPatientBalance(detail.patientId)
}

// 加载联系结果选项
const loadContactResultOptions = async () => {
  try {
    const response = await api.post('/api/Dict/get-by-dict-id', {
      dictId: 7
    })
    
    if (response.data && Array.isArray(response.data)) {
      contactResultOptions.value = response.data
    } else {
      contactResultOptions.value = []
      console.warn('联系结果字典数据格式不正确:', response.data)
    }
  } catch (error) {
    console.error('加载联系结果选项失败:', error)
    contactResultOptions.value = []
    showToast('加载联系结果选项失败: ' + (error.response?.data?.message || error.message), 'error')
  }
}

// 加载患者HIS余额
const loadPatientBalance = async (patientId) => {
  if (!patientId) {
    patientBalanceError.value = '患者ID为空'
    return
  }
  
  patientBalanceLoading.value = true
  patientBalanceError.value = ''
  patientBalance.value = 0
  
  try {
    const response = await api.get(`/api/refund/patient-balance/${patientId}`)
    
    if (response.data && response.data.success) {
      patientBalance.value = response.data.data.balance || 0
    } else {
      patientBalanceError.value = response.data?.message || '查询余额失败'
    }
  } catch (error) {
    console.error('查询患者余额失败:', error)
    patientBalanceError.value = '查询余额失败: ' + (error.response?.data?.message || error.message)
  } finally {
    patientBalanceLoading.value = false
  }
}

// 检测数据是否有更改
const checkForChanges = () => {
  if (!selectedContactDetail.value || !originalContactData.value) {
    hasUnsavedChanges.value = false
    hasContactResultChanges.value = false
    return
  }
  
  // 检查联系结果字段的变化
  const contactResultFields = ['notes1', 'notes2', 'notes3', 'notes4', 'notes5']
  let hasContactChanges = false
  
  for (const field of contactResultFields) {
    const original = originalContactData.value[field] || ''
    const current = selectedContactDetail.value[field] || ''
    if (current !== original) {
      hasContactChanges = true
      break
    }
  }
  
  // 检查备注字段的变化
  const userNotesFields = ['userNotes1', 'userNotes2', 'userNotes3', 'userNotes4', 'userNotes5']
  let hasNotesChanges = false
  
  for (const field of userNotesFields) {
    const original = originalContactData.value[field] || ''
    const current = selectedContactDetail.value[field] || ''
    if (current !== original) {
      hasNotesChanges = true
      break
    }
  }
  
  hasContactResultChanges.value = hasContactChanges
  hasUnsavedChanges.value = hasContactChanges || hasNotesChanges
}

// 获取联系记录列表 - 始终返回5条记录
const getContactRecords = (detail) => {
  if (!detail) return []
  
  const records = []
  
  // 处理5个联系记录字段，始终显示5条记录
  for (let i = 1; i <= 5; i++) {
    const contactTime = detail[`contactTime${i}`]
    const notes = detail[`notes${i}`]
    const userNotes = detail[`userNotes${i}`]
    
    records.push({
      index: i,
      contactTime: contactTime,
      notes: notes,
      userNotes: userNotes
    })
  }
  
  return records
}

// 监听notes变化
const onNotesChange = (index) => {
  checkForChanges()
}

// 联系结果选择变化处理
const onContactResultChange = async (index) => {
  // 跟踪选择联系结果行为
  const contactResult = selectedContactDetail.value[`notes${index}`]
  // await userBehaviorService.trackSelectContactResult(index, contactResult)
  
  checkForChanges()
}

// 用户备注输入处理
const onUserNotesInput = async (index) => {
  // 跟踪输入备注行为
  const notesText = selectedContactDetail.value[`userNotes${index}`] || ''
  // await userBehaviorService.trackInputNotes(index, notesText)
  
  checkForChanges()
}

// 检查联系记录是否已保存
const isContactRecordSaved = (index) => {
  if (!selectedContactDetail.value) return false
  const notes = selectedContactDetail.value[`notes${index}`]
  const contactTime = selectedContactDetail.value[`contactTime${index}`]
  return notes && contactTime
}

// 检查是否可以编辑联系记录
const canEditContactRecord = (index) => {
  if (!selectedContactDetail.value) return false
  
  // 第一次联系总是可以编辑
  if (index === 1) return true
  
  // 其他次数需要前一次已经保存
  const prevIndex = index - 1
  return isContactRecordSaved(prevIndex)
}

// 关闭联系对话框
const closeContactDialog = async () => {
  // 使用统一的未保存更改检查
  if (hasUnsavedChanges.value || hasContactResultChanges.value) {
    if (!confirm('当前有未保存的更改，确定要关闭吗？未保存的数据将丢失。')) {
      return
    }
    
    // 完成会话（未保存关闭', '用户关闭对话框但未保存')
    // await userBehaviorService.completeSession('未保存关闭', '用户关闭对话框但未保存')
    
    // 重置状态
    hasUnsavedChanges.value = false
    hasContactResultChanges.value = false
  } else {
    // 完成会话（正常关闭）
    // await userBehaviorService.completeSession('正常关闭', '用户正常关闭对话框')
  }
  
  showContactDialog.value = false
}

// 保存联系记录
const saveContactRecord = async () => {
  if (!selectedContactDetail.value) return
  
  // 检查患者余额
  if (patientBalance.value === 0) {
    showToast('患者余额为0，无法保存联系记录', 'warning')
    return
  }
  
  // 检查是否有联系结果的变化
  if (!hasContactResultChanges.value) {
    showToast('请选择联系结果后再保存', 'warning')
    return
  }
  
  try {
    // 跟踪保存联系记录行为
    // await userBehaviorService.trackSaveContact({
    //   contactCount: selectedContactDetail.value.contactCount || 0,
    //   userNotes: selectedContactDetail.value.userNotes1 || '',
    //   contactResult: selectedContactDetail.value.notes1 || '已保存',
    //   patientId: selectedContactDetail.value.patientId
    // })
    
    // 获取当前时间，格式化为 ISO 字符串
    const currentTime = new Date().toISOString();
    
    // 计算实际的联系次数 - 根据填写的notes数量
    let actualContactCount = 0;
    const notesFields = ['notes1', 'notes2', 'notes3', 'notes4', 'notes5'];
    for (const field of notesFields) {
      if (selectedContactDetail.value[field] && selectedContactDetail.value[field].trim() !== '') {
        actualContactCount++;
      }
    }
    
    // 构建更新请求数据，包含完整的记录信息
    const updateData = {
      id: selectedContactDetail.value.id,
      masterId: selectedContactDetail.value.masterId,
      patientId: selectedContactDetail.value.patientId,
      accountId: selectedContactDetail.value.accountId,
      accountIndex: selectedContactDetail.value.accountIndex,
      balance: selectedContactDetail.value.balance,
      contactCount: actualContactCount, // 使用计算出的实际联系次数
      phoneNumber: selectedContactDetail.value.phoneNumber,
      patName: selectedContactDetail.value.patName,
      idNumber: selectedContactDetail.value.idNumber,
      sex: selectedContactDetail.value.sex,
      nextOfKin: selectedContactDetail.value.nextOfKin,
      // 联系记录字段 - 如果有联系结果则自动设置当前时间
      contactTime1: selectedContactDetail.value.contactTime1 || (selectedContactDetail.value.notes1 ? currentTime : null),
      notes1: selectedContactDetail.value.notes1,
      userNotes1: selectedContactDetail.value.userNotes1,
      contactTime2: selectedContactDetail.value.contactTime2 || (selectedContactDetail.value.notes2 ? currentTime : null),
      notes2: selectedContactDetail.value.notes2,
      userNotes2: selectedContactDetail.value.userNotes2,
      contactTime3: selectedContactDetail.value.contactTime3 || (selectedContactDetail.value.notes3 ? currentTime : null),
      notes3: selectedContactDetail.value.notes3,
      userNotes3: selectedContactDetail.value.userNotes3,
      contactTime4: selectedContactDetail.value.contactTime4 || (selectedContactDetail.value.notes4 ? currentTime : null),
      notes4: selectedContactDetail.value.notes4,
      userNotes4: selectedContactDetail.value.userNotes4,
      contactTime5: selectedContactDetail.value.contactTime5 || (selectedContactDetail.value.notes5 ? currentTime : null),
      notes5: selectedContactDetail.value.notes5,
      userNotes5: selectedContactDetail.value.userNotes5
    };

    // 调用正确的后台接口
    const response = await api.post('/api/RefundTaskDetail/update', updateData);

    if (response.data) {
      // 更新原始数据备份
      originalContactData.value = JSON.parse(JSON.stringify(selectedContactDetail.value))
      hasUnsavedChanges.value = false
      hasContactResultChanges.value = false
      
      showToast('联系记录保存成功', 'success');
      // 更新详情数据中的对应记录
      const detailIndex = detailData.value.findIndex(item => item.id === selectedContactDetail.value.id);
      if (detailIndex !== -1) {
        Object.assign(detailData.value[detailIndex], updateData);
        // 同时更新当前显示的联系详情
        Object.assign(selectedContactDetail.value, updateData);
        
        // 更新任务对象中的详情数据
        const taskIndex = masterData.value.findIndex(task => task.id === selectedContactDetail.value.masterId);
        if (taskIndex !== -1 && masterData.value[taskIndex].details) {
          const taskDetailIndex = masterData.value[taskIndex].details.findIndex(detail => detail.id === selectedContactDetail.value.id);
          if (taskDetailIndex !== -1) {
            Object.assign(masterData.value[taskIndex].details[taskDetailIndex], updateData);
          }
        }
      }
      
      // 重新加载最新任务详情以更新创建按钮状态
      await loadLatestTaskDetails()
      
      // 重新加载联系统计数以更新联系进度
      await loadContactStatsForAllTasks()
      
      // 完成会话（保存成功）
      const contactResult = selectedContactDetail.value.notes1 || '已保存'
      // await userBehaviorService.completeSession(contactResult, selectedContactDetail.value.userNotes1 || '')
      
      // 显示保存后的选择对话框
      showSaveActionDialog()
    } else {
      throw new Error('保存失败');
    }
  } catch (error) {
    console.error('保存联系记录失败:', error)
    showToast('保存联系记录失败: ' + (error.response?.data?.message || error.message), 'error')
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  
  try {
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) return dateTime
    
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return dateTime
  }
}

// 刷新数据
const refreshData = () => {
  loadMasterData()
}

// 格式化货币
// 货币格式化
const formatCurrency = (amount) => {
  if (amount === null || amount === undefined) return '¥0.00'
  return '¥' + Number(amount).toFixed(2)
}

// 获取行样式类
const getRowClass = (detail) => {
  const contactCount = detail.contactCount || 0
  if (contactCount === 0) {
    return 'table-warning' // 未联系的行使用警告色
  }
  return ''
}

// 获取联系次数样式类
const getContactCountClass = (contactCount) => {
  const count = contactCount || 0
  if (count === 0) {
    return 'badge bg-warning text-dark fw-bold'
  } else if (count === 1) {
    return 'badge bg-info text-white'
  } else if (count >= 2) {
    return 'badge bg-success text-white'
  }
  return 'badge bg-secondary'
}



// 获取创建任务按钮的提示信息
const getCreateTaskButtonTitle = () => {
  if (loading.value) {
    return '正在处理中...'
  }
  
  if (masterData.value.length === 0) {
    return '创建第一个退费任务'
  }
  
  if (!canCreateNewTask.value) {
    const uncontactedCount = latestTaskDetails.value.filter(detail => (detail.contactCount || 0) === 0).length
    return `当前任务中还有 ${uncontactedCount} 位患者未联系，请先完成联系工作`
  }
  
  return '创建新的退费任务'
}

// 获取联系进度百分比
const getProgressPercentage = (contactedCount, totalCount) => {
  if (!totalCount || totalCount === 0) return 0
  const percentage = Math.round((contactedCount / totalCount) * 100)
  return Math.min(percentage, 100)
}

// 获取进度条样式类
const getProgressBarClass = (contactedCount, totalCount) => {
  const percentage = getProgressPercentage(contactedCount, totalCount)
  
  if (percentage === 100) {
    return 'bg-success' // 绿色 - 全部完成
  } else if (percentage >= 80) {
    return 'bg-info' // 蓝色 - 接近完成
  } else if (percentage >= 50) {
    return 'bg-warning' // 黄色 - 进行中
  } else if (percentage > 0) {
    return 'bg-primary' // 主色 - 刚开始
  } else {
    return 'bg-secondary' // 灰色 - 未开始
  }
}

// 切换沟通指引展开状态
const toggleGuideExpanded = () => {
  guideExpanded.value = !guideExpanded.value
}

// 复制电话号码
const copyPhoneNumber = async (phoneNumber) => {
  try {
    await navigator.clipboard.writeText(phoneNumber)
    showToast('电话号码已复制到剪贴板', 'success')
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = phoneNumber
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    showToast('电话号码已复制到剪贴板', 'success')
  }
}

// 复制文本到剪贴板
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    showToast('已复制到剪贴板', 'success')
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    showToast('已复制到剪贴板', 'success')
  }
}

// 上一条详情
const prevDetail = () => {
  if (currentDetailIndex.value > 0) {
    currentDetailIndex.value--
  }
}

// 下一条详情
const nextDetail = () => {
  if (currentDetailIndex.value < detailData.value.length - 1) {
    currentDetailIndex.value++
  }
}

// 检查是否有未保存的更改并提示用户
const checkUnsavedChanges = () => {
  if (hasUnsavedChanges.value || hasContactResultChanges.value) {
    return confirm('当前有未保存的更改，确定要离开吗？未保存的数据将丢失。')
  }
  return true
}

// 上一条联系记录
const prevContactRecord = () => {
  // 检查未保存的更改
  if (!checkUnsavedChanges()) {
    return
  }
  
  if (currentContactIndex.value > 0) {
    const prevIndex = currentContactIndex.value - 1
    // 修改：使用排序后的数据进行导航
    const prevDetailRecord = sortedDetailData.value[prevIndex]
    if (prevDetailRecord) {
      showContactRecord(prevDetailRecord)
    }
  }
}

// 下一条联系记录
const nextContactRecord = () => {
  // 检查未保存的更改
  if (!checkUnsavedChanges()) {
    return
  }
  
  // 修改：使用排序后的数据长度进行边界检查
  if (currentContactIndex.value < sortedDetailData.value.length - 1) {
    const nextIndex = currentContactIndex.value + 1
    // 修改：使用排序后的数据进行导航
    const nextDetailRecord = sortedDetailData.value[nextIndex]
    if (nextDetailRecord) {
      showContactRecord(nextDetailRecord)
    }
  }
}

// 保存后操作选择相关状态
const showSaveActionDialogFlag = ref(false)

// 显示保存后操作选择对话框
const showSaveActionDialog = () => {
  showSaveActionDialogFlag.value = true
}

// 跳转到下一条记录
const goToNextRecord = () => {
  showSaveActionDialogFlag.value = false
  nextContactRecord()
}

// 继续处理当前记录
const stayCurrentRecord = () => {
  showSaveActionDialogFlag.value = false
  // 保持在当前记录，不做任何操作
}
</script>

<style scoped>
.refund-task-management {
  padding: 1rem 0;
}

.table th {
  white-space: nowrap;
}

.table td {
  vertical-align: middle;
}

.modal-xl {
  max-width: 95%;
}

/* 联系进度样式 */
.contact-progress {
  min-width: 120px;
}

.contact-progress .progress {
  border-radius: 10px;
  background-color: #e9ecef;
}

.contact-progress .progress-bar {
  border-radius: 10px;
  transition: width 0.3s ease;
}

/* 电话号码高亮样式 */
.phone-number-highlight {
  display: inline-flex;
  align-items: center;
  padding: 0.25rem 0.5rem;
  background-color: #f8f9fa;
  border: 2px solid #007bff;
  border-radius: 0.375rem;
  margin-left: 0.5rem;
}

.phone-number-highlight .text-primary {
  font-weight: 600;
  letter-spacing: 0.5px;
}

/* 沟通指引样式 */
.communication-terms .term-item {
  padding: 0.5rem;
  background-color: #f8f9fa;
  border-left: 3px solid #007bff;
  margin-bottom: 0.5rem;
  border-radius: 0.25rem;
}

.communication-scripts .script-category {
  border: 1px solid #e9ecef;
  border-radius: 0.25rem;
  padding: 0.75rem;
  background-color: #fdfdfe;
}

.script-item:hover {
  background-color: #e3f2fd;
  border-radius: 0.25rem;
  padding: 0.25rem 0.5rem;
  transition: background-color 0.2s ease;
}

.notes-list .note-item {
  padding: 0.25rem 0.5rem;
  background-color: #fff3cd;
  border-left: 3px solid #ffc107;
  margin-bottom: 0.25rem;
  border-radius: 0.25rem;
}

@media (max-width: 768px) {
  .modal-xl {
    max-width: 100%;
    margin: 0.5rem;
  }
  
  .phone-number-highlight {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .phone-number-highlight .btn {
    margin-top: 0.25rem;
    margin-left: 0;
  }
  
  .contact-progress {
    min-width: 100px;
  }
}
</style>